// 缓存数据
export const writeData = (params) => {
    let { module, key, data } = params
    let cacheData = {}
    try {
        cacheData = JSON.parse(sessionStorage.getItem(module))
    } catch (e) {
        alert('当前浏览器不支持sessionStorage,请勿使用无痕模式')
    }
    if (key === undefined) {
        sessionStorage.setItem(module, JSON.stringify(data))
    } else {
        Object.assign(cacheData[key], data)
        sessionStorage.setItem(module, JSON.stringify(cacheData))
    }
}

// 获取缓存
export const readData = (params) => {
    let { module, key } = params
    let cacheData
    try {
        cacheData = JSON.parse(sessionStorage.getItem(module))
    } catch (e) {
        alert('当前浏览器不支持sessionStorage,请勿使用无痕模式')
    }
    if (key === undefined) {
        return cacheData
    } else {
        return cacheData[key]
    }
}

// 清除缓存
export const clearData = (params) => {
    let { module } = params
    sessionStorage.removeItem(module)
}

// 时间格式处理-times(19971129213155)
export const timeFormatHandle = (times) => {
    let ntime = times
    // 转成字符串
    if (typeof ntime === 'number') {
        ntime = ntime.toString()
    }
    // 为0时返回空
    if (ntime === '0' || ntime === '') {
        return ''
    }
    let y = ntime.substring(0, 4)
    let m = ntime.substring(4, 6)
    let d = ntime.substring(6, 8)
    let h = ntime.substring(8, 10)
    let n = ntime.substring(10, 12)
    let s = ntime.substring(12, 15)
    return y + '-' + m + '-' + d + ' ' + h + ':' + n + ':' + s
}

// 处理基础数据返回值
export const handleBasicVal = (object, listdata) => {
    let ns = {}
    if (listdata) {
        ns = listdata.find(item => item.value === object.value)
    } else {
        ns = window.basicData[object.name].find(item => item.value === object.value)
    }
    return ns.name || ''
}

// 时间格式处理，将Date格式的时间转换为"YYYY-mm-dd HH:ii:ss"格式
export const formatDate = (date) => {
    if (date === undefined || date === '') {
        return ''
    }
    function addLength (str) {
        if (str.length === 1) {
            return '0' + str
        }
        return str
    }
    let year = date.getFullYear().toString()
    let month = addLength((date.getMonth() + 1).toString())
    let day = addLength(date.getDate().toString())
    let hour = addLength(date.getHours().toString())
    let minute = addLength(date.getMinutes().toString())
    let second = addLength(date.getSeconds().toString())

    return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
}
